package com.example.fresh_market.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.fresh_market.R;
import com.example.fresh_market.constants.RegexConstant;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.http.HttpStatus;

public class RegisterActivity extends AppCompatActivity {

    private EditText username_et;
    private EditText password_et;
    private EditText confirmPassword_et;
    private Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = this;
        username_et = findViewById(R.id.username);
        password_et = findViewById(R.id.password);
        Button register_btn = findViewById(R.id.register);
        confirmPassword_et = findViewById(R.id.confirm_password);
        register_btn.setOnClickListener(v -> register());
        TextView toLogin = findViewById(R.id.toLogin);
        toLogin.setOnClickListener(v -> turnToLogin());
    }

    private void register() {
        String username = username_et.getText().toString().trim();
        String password = password_et.getText().toString().trim();
        String confirmPassword = confirmPassword_et.getText().toString().trim();
        if (!username.matches(RegexConstant.USERNAME)) {
            ToastUtil.showToast(this, "用户名格式错误");
            return;
        }
        if (!password.matches(RegexConstant.PASSWORD)) {
            ToastUtil.showToast(this, "密码格式错误");
            return;
        }
        if (!confirmPassword.equals(password)) {
            ToastUtil.showToast(this, "两次输入的密码不一致");
            return;
        }
        Map<String, String> params = new HashMap<>();
        // 在这里添加表单字段
        params.put("username", username);
        params.put("password", password);
        params.put("confirmPassword", confirmPassword);
        params.put("role", "user");
        HttpUtil.post(mContext, "/user/register", params, response -> {
            Log.d("", response);
            ApiResponse apiResponse = new Gson().fromJson(response, ApiResponse.class);
            if (apiResponse.getCode() == HttpStatus.HTTP_OK) {
                ToastUtil.showToast(mContext, "注册成功");
                turnToLogin();
            }
        });
    }

    private void turnToLogin() {
        startActivity(new Intent(this, LoginActivity.class));
    }
}
